'use strict';

import Vue from 'vue'
import Vuex from 'vuex'

import AppStorage from '../kit/AppStorage'


Vue.use(Vuex)


const state = {
	user: {
		apiToken: '',
		apiUserId: 0,
		permList: [],
		role:'',
		address: '',
		userPhone: 0
	},
	shop: {
		id: 0,
		title: ''
	},
}

function init(){
	let user = AppStorage.getItemJson('user');
	if (user) {
		state.user.apiToken = user.apiToken;
		state.user.apiUserId = user.apiUserId;
		state.user.permList = user.permList;
		state.user.role = user.role;
		state.user.address = user.address;
		state.user.userPhone = user.userPhone;
 	}

	let shop = AppStorage.getItemJson('shop');
	if (shop) {
		state.shop.id = shop.id;
		state.shop.title = shop.title;
	}
}


init();


const storeClearUser = ()=>{
	state.user.apiToken = '';
	state.user.apiUserId = 0;
	state.user.permList = [];
	state.user.role = 0
	
	state.shop.id = 0;
	state.shop.title = '';

	AppStorage.clear();
}


const mutations = {
	setUser(state, {apiToken, apiUserId, role, address,userPhone}) {
		state.user.apiToken = apiToken;
		state.user.apiUserId = apiUserId;
		state.user.role = role;
		state.user.address = address;
		state.user.userPhone = userPhone;
		AppStorage.setItemJson('user', state.user);
	},
	clearUser(state) {
		state.user.apiToken = '';
		state.user.apiUserId = 0;
		state.user.permList = [];
		state.user.role = 0
		state.user.address = '';
		state.user.userPhone = 0;

		state.shop.id = 0;
		state.shop.title = '';

		AppStorage.clear();
	},
	setShop(state, {id, title}) {
		state.shop.id = id;
		state.shop.title = title;

		AppStorage.setItemJson('shop', state.shop);
	},
}


const getters = {
	hasPerm(state, getters) {
		return (perm) => {
			let permList = state.user.permList;

			for (var i = 0; i < permList.length; i++) {
				let permVal = permList[i];
				if (perm == permVal) {
					return true;
				}
			}
			return false;
		}
	},
	hasPerms(state, getters) {
		return (permArr) => {
			let permList = state.user.permList;

			for (var i = 0; i < permList.length; i++) {
				let permVal = permList[i];

				for (var j = 0; j < permArr.length; j++) {
					let perm = permArr[j];
					if (permVal == perm) {
						return true;
					}
				}
			}
			return false;
		}
	}
}


export default new Vuex.Store({
	state,
	mutations,
	getters,
	storeClearUser
})